<?php
/**
 * //w/w/w.s/h/u/o/t//u/p/u c/o/m  说/图/谱/源/码/分/享
 */
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/12 0012
 * Time: 17:12
 */
defined("IN_IA")or exit("Access denied");
global $_GPC,$_W;
$uniacid=$_W['uniacid'];
$op=$_GPC['op'] ? $_GPC['op'] :"about_us";
if($op=='about_us'){
    $list=pdo_get("cqkundian_farm_about",array('uniacid'=>$uniacid));
    include $this->template("web/system/about");
}
if($op=='about_save'){
    $insertData=array(
        'phone'=>trim($_GPC['phone']),
        'uniacid'=>$uniacid,
        'send_price'=>$_GPC['send_price'],
        'farm_name'=>$_GPC['farm_name'],
        'add_price'=>$_GPC['add_price'],
        'home_title'=>$_GPC['home_title'],
        'vet_banner'=>tomedia($_GPC['vet_banner']),
        'sign_banner'=>tomedia($_GPC['sign_banner']),
        'is_open_vet'=>$_GPC['is_open_vet'],
        'farm_desc'=>$_GPC['farm_desc'],
    );
    if(empty($_GPC['id'])){
        $res=pdo_insert('cqkundian_farm_about',$insertData);
    }else{
        $res=pdo_update('cqkundian_farm_about',$insertData,array('uniacid'=>$uniacid,'id'=>$_GPC['id']));
    }
    if($res){
        message('操作成功',$this->createWebUrl('system'));
    }else{
        message("操作失败");
    }
    die;
}

//微信配置
if($op=='wx_set'){
    $list=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    $wx_openid=unserialize($list['get_openid']);
    include $this->template("web/system/wx_set");
}

if($op=='wx_set_save'){
    $updateData=array(
        'wx_appid'=>$_GPC['wx_appid'],
        'wx_secret'=>$_GPC['wx_secret'],
        'wx_template_order_id'=>$_GPC['wx_template_order_id'],
        'wx_shop_template_id'=>$_GPC['wx_shop_template_id'],
        'wx_cancel_template_id'=>$_GPC['wx_cancel_template_id'],
        'uniacid'=>$uniacid,
    );

    if($_FILES['wx_key']['name']!=''){
        $updateData['wx_key']=uploadPem($_FILES['wx_key']);
    }
    if($_FILES['wx_cert']['name']!=''){
        $updateData['wx_cert']=uploadPem($_FILES['wx_cert']);
    }
    if(empty($_GPC['id'])){
        $res=pdo_insert("cqkundian_farm_wx_set",$updateData);
    }else{
        $res=pdo_update("cqkundian_farm_wx_set",$updateData,array('id'=>$_GPC['id'],'uniacid'=>$uniacid));
    }
    if($res){
        message("操作成功",url('site/entry/system',array('m'=>'kundian_farm','op'=>'wx_set')));
    }else{
        message('操作失败');
    }
}

if($op=='sign_set'){
    $list=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    include $this->template('web/system/sign_set');
}

if($op=='sign_save'){
    $insertData=array(
        'sign_integral'=>trim($_GPC['sign_integral']),
        'pay_integral'=>$_GPC['pay_integral'],
        'sign_rule'=>$_GPC['sign_rule'],
    );
    if(empty($_GPC['id'])){
        $res=pdo_insert('cqkundian_farm_about',$insertData);
    }else{
        $res=pdo_update('cqkundian_farm_about',$insertData,array('uniacid'=>$uniacid,'id'=>$_GPC['id']));
    }
    if($res){
        message('操作成功',url('site/entry/system',array('m'=>'kundian_farm','op'=>'sign_set')));
    }else{
        message("操作失败");
    }
    die;
}

if($op=='qcode') {           //生成授权二维码
    $wxData = pdo_get('cqkundian_farm_wx_set', array('uniacid' => $uniacid));
    include 'phpqrcode/phpqrcode.php';
     //二维码内容
    $oldStr = url('site/entry/system', array('m' => 'kundian_farm', 'op' => 'shouquan', 'version_id' => $_GPC['version_id'], 'uniacid' => $uniacid, 'id' => $_GPC['id']));
    $oldStr = ltrim($oldStr, ".");
    $nowStr = $_W['siteroot'] . 'web' . $oldStr;
    $errorCorrectionLevel = 'L';    //容错级别
    $matrixPointSize = 5;           //生成图片大小
    //生成二维码图片
    $QR = QRcode::png($nowStr, false, $errorCorrectionLevel, $matrixPointSize, 2);
    var_dump($QR);
    die;
}
if($op=='shouquan') {  //收取获取code
    $wxData = pdo_get('cqkundian_farm_wx_set', array('uniacid' => $_GPC['uniacid']));
    $appid = $wxData['wx_appid'];
    $oldStr = url('site/entry/system', array('m' => 'kundian_farm', 'op' => 'getOpenid', 'version_id' => $_GPC['version_id'], 'uniacid' => $_GPC['uniacid'], 'id' => $_GPC['id']));
    $oldStr = ltrim($oldStr, ".");
    $nowStr = $_W['siteroot'] . 'web' . $oldStr;
    $redirect_uri = urlencode($nowStr);
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    header("Location:" . $url);
}
if($op=='getOpenid') {       //获取用户的openid
    $jump_url=$_W['siteroot'];
    $wxData = pdo_get('cqkundian_farm_wx_set', array('uniacid' => $_GPC['uniacid']));

    $appid = $wxData['wx_appid'];
    $secret = $wxData['wx_secret'];
    $code = $_GET["code"];
    //第一步:取得openid
    $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
    $oauth2 = getJson($oauth2Url);
    //第二步:根据全局access_token和openid查询用户信息
    $openid = $oauth2['openid'];
    $id = $_GPC['id'];
    if ($openid) {
        $shopData = pdo_get('cqkundian_farm_wx_set', array('uniacid' => $_GPC['uniacid']));
        $wx_openid = unserialize($shopData['get_openid']);
        if (empty($wx_openid)) {
            $wx_openid[] = $openid;
        } else {
            for ($i = 0; $i < count($wx_openid); $i++) {
                if ($wx_openid[$i] == $openid) {
                    echo "<script>alert('已授权!');</script>";
                    die;
                }
            }
            array_push($wx_openid, $openid);
        }
        $res = pdo_update('cqkundian_farm_wx_set', array('get_openid' => serialize($wx_openid)), array('uniacid' => $_GPC['uniacid']));
        if ($res) {
            echo "<script>alert('授权成功！');</script>";
        } else {
            echo "<script>alert('已授权！');</script>";
        }
    } else {
        echo "<script>alert('授权失败！');</script>";
    }
}

if($op=="deleteOpenid"){
    $id=$_GPC['id'];
    $shopData=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    $wx_openid=unserialize($shopData['get_openid']);
    array_splice($wx_openid,$id,1);
    $res=pdo_update('cqkundian_farm_wx_set',array('get_openid'=>serialize($wx_openid)),array('uniacid'=>$uniacid));
    echo  $res ? json_encode(array('status'=>1)) : json_encode(array('status'=>2));
}

//农场天气设置
if($op=='weather_set'){
    $list=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    include $this->template("web/system/weather_set");
}
//农场天气保存
if($op=='weather_save'){
    $insertData=array(
        'uniacid'=>$uniacid,
        'longitude'=>$_GPC['longitude'],
        'latitude'=>$_GPC['latitude'],
        'appcode'=>$_GPC['appcode'],
        'is_open_weather'=>$_GPC['is_open_weather'],
    );

    if(empty($_GPC['id'])){
        $res=pdo_insert('cqkundian_farm_wx_set',$insertData);
    }else{
        $res=pdo_update('cqkundian_farm_wx_set',$insertData,array('uniacid'=>$uniacid,'id'=>$_GPC['id']));
    }
    if($res){
        $url=url('site/entry/system',array('m'=>'kundian_farm','op'=>'weather_set'));
        message('操作成功',$url);
    }else{
        message("操作失败");
    }
    die;
}

if($op=='farm_rule'){
    $list=pdo_get('cqkundian_farm_set',array('ikey'=>'farm_rule','uniacid'=>$uniacid));
    include $this->template('web/system/farm_rule');
}

if($op=='farm_rule_save'){
    $data=$_POST;
    $res=0;
    foreach ($data as $key=>$v){
        $updateData=array(
            'ikey'=>$key,
            'value'=>$v,
            'uniacid'=>$uniacid,
        );
        $cond=array(
            'ikey'=>$key,
            'uniacid'=>$uniacid,
        );
        $farmData=pdo_get('cqkundian_farm_set',$cond);
        if(empty($farmData)){
            $res+=pdo_insert('cqkundian_farm_set',$updateData);
        }else{
            $res+=pdo_update('cqkundian_farm_set',$updateData,$cond);
        }
    }
    if($res){
        message('操作成功',url('site/entry/system',array('m'=>'kundian_farm','op'=>'farm_rule')));die;
    }else{
        message('操作失败');
    }
}

//小程序顶部颜色设置
if($op=='miniapp_nav_color'){
    $condition=array(
        'ikey'=>array('front_color','background_color','center_back_color'),
        'uniacid'=>$uniacid,
    );
    $list=pdo_getall('cqkundian_farm_set',$condition);
    $nowList=array();
    foreach ($list as $key => $value) {
        $nowList[$value['ikey']]=$value['value'];
    }
    include $this->template('web/system/miniapp_nav_color');
}

if($op=='miniapp_nav_color_save'){
    $data=$_POST;
    $res=0;
    foreach ($data as $key=>$v){
        $updateData=array(
            'ikey'=>$key,
            'value'=>$v,
            'uniacid'=>$uniacid,
        );
        $cond=array(
            'ikey'=>$key,
            'uniacid'=>$uniacid,
        );
        $farmData=pdo_get('cqkundian_farm_set',$cond);
        if(empty($farmData)){
            $res+=pdo_insert('cqkundian_farm_set',$updateData);
        }else{
            $res+=pdo_update('cqkundian_farm_set',$updateData,$cond);
        }
    }
    if($res){
        message('操作成功',url('site/entry/system',array('m'=>'kundian_farm','op'=>'miniapp_nav_color')));die;
    }else{
        message('操作失败');
    }
}

//分享描述设置
if($op=='share_title_set'){
    $condition=array(
        'ikey'=>array('share_home_title','share_shop_title','share_land_title','share_animal_title'),
        'uniacid'=>$uniacid,
    );
    $list1=pdo_getall('cqkundian_farm_set',$condition);
    $list=array();
    foreach ($list1 as $key => $value) {
        $list[$value['ikey']]=$value['value'];
    }
    include $this->template("web/system/share_title_set");
}

//分享描述转发
if($op=='share_title_save'){
    $data=$_POST;
    $res=insertSetData($data,$uniacid);
    if($res){
        message('操作成功',url('site/entry/system',array('m'=>'kundian_farm','op'=>'share_title_set')));die;
    }else{
        message('操作失败');
    }
}

//微信小程序模板消息设置
if($op=='mini_template_set'){
    $list=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    $siteroot=$_W['siteroot'];
    include $this->template("web/system/mini_template_set");
}

//微信小程序模板消息设置保存
if($op=='mini_template_set_save'){

    $updateData=array(
        'wx_small_template_id'=>$_GPC['wx_small_template_id'],
        'mini_device_template_id'=>$_GPC['mini_device_template_id'],
        'mini_services_template_id'=>$_GPC['mini_services_template_id'],
        'uniacid'=>$uniacid,
    );
    if(empty($_GPC['id'])){
        $res=pdo_insert("cqkundian_farm_wx_set",$updateData);
    }else{
        $res=pdo_update("cqkundian_farm_wx_set",$updateData,array('id'=>$_GPC['id'],'uniacid'=>$uniacid));
    }
    if($res){
        message("操作成功",url('site/entry/system',array('m'=>'kundian_farm','op'=>'mini_template_set')));
    }else{
        message('操作失败');
    }
}


/**
 * 配置信息插入
 * @param $data
 * @param $uniacid
 * @return bool|int
 */
function insertSetData($data,$uniacid){
    $res=0;
    foreach ($data as $key=>$v){
        $updateData=array(
            'ikey'=>$key,
            'value'=>$v,
            'uniacid'=>$uniacid,
        );
        $cond=array(
            'ikey'=>$key,
            'uniacid'=>$uniacid,
        );
        $farmData=pdo_get('cqkundian_farm_set',$cond);
        if(empty($farmData)){
            $res+=pdo_insert('cqkundian_farm_set',$updateData);
        }else{
            $res+=pdo_update('cqkundian_farm_set',$updateData,$cond);
        }
    }

    return $res;

}

/**
 * 微擎原始文件上传文件（pem文件）
 * @param $file
 * @return bool
 */
function uploadPem($file){
    global $_W;
    $dir_url=ATTACHMENT_ROOT.'/kundian_farm/'.$_W['uniacid']."/"; //上传路径
    mkdirs($dir_url); //创建目录
    if (($file["type"] == "application/octet-stream") && ($file["size"] < 20000)) {
        if ($file["error"] > 0){
            echo false;
        }
        else{
            if (file_exists("upload/" . $file["name"])){
                return false;
            }
            else{
                $res=move_uploaded_file($file["tmp_name"],$dir_url . $file["name"]);
                if($res){
                    return $dir_url.$file['name'];
                }else{
                    return false;
                }
            }
        }
    }
    else{
        return false;
    }
}

function getJson($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);
}




